﻿using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using Server.Business.proto;
using Server.Database;
using Server.Resource;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Server.Business
{
    public class UserBusiness
    {
        private MongoDatabase _database;
        private MongoCollection<UserDB> _userArray;

        private MongoCollection<UserDB> UserArray
        {
            get
            {
                if (_userArray == null)
                    _userArray = Database.GetCollection<UserDB>("UserDB");
                return _userArray;
            }
        }

        private MongoDatabase Database
        {
            get
            {
                if (_database == null)
                {
                    MongoClient client = new MongoClient(ServerConfig.Singleton.Database);
                    MongoServer server = client.GetServer();
                    _database = server.GetDatabase("zcdb");
                }
                return _database;
            }
        }

        public IEnumerable<UserDB> GetUsers()
        {
            return UserArray.FindAll();
        }

        public string AddUser(User user)
        {
            UserDB instance = new UserDB();
            instance.Name = user.Name;
            instance.Pwd = user.Password;
            instance.RoleType = user.RoleType;
            UserArray.Insert(instance);
            return instance.Id.ToString();
        }

        public bool UpdateUser(User user)
        {
            var update = Update.Set("Pwd", user.Password).Set("RoleType", user.RoleType);
            return UserArray.Update(Query.EQ("_id", ObjectId.Parse(user.Id)), update).Ok;
        }

        public bool DeleteUser(string id)
        {
            return UserArray.Remove(Query.EQ("_id", ObjectId.Parse(id))).Ok;
        }

        public UserDB Login(string name, string pwd)
        {
            return UserArray.FindOne(Query.And(Query.EQ("Name", name), Query.EQ("Pwd", pwd)));
        }
    }
}
